package com.shadt.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.shadt.core.model.Json;

/**
 * 发送短息帮助类
 * @author SongR
 *
 */
public class SendUtil {
	
	/**
	 * post请求
	 * @param httpUrl:请求接口
	 * @param httpArg:参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
		PrintWriter out = null;
		BufferedReader buff = null;
		StringBuffer result = new StringBuffer();
		try {
			URL realUrl = new URL(httpUrl);
			URLConnection conn = realUrl.openConnection();// 打开和URL之间的连接
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			out.print(httpArg);	// 发送请求参数
			out.flush();// flush输出流的缓冲
			// 定义BufferedReader输入流来读取URL的响应
			// 获取页面内容
			InputStream in = conn.getInputStream();
			buff = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String str = buff.readLine();
			while (str != null) {
				result.append(str);
				str = buff.readLine();
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (buff != null) {
					buff.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}
	
	/**
	 * 解析xml
	 * @param protocolXML
	 * @return
	 */
	public static Json parse(String protocolXML) {
		Json j = new Json();
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(new InputSource(new StringReader(protocolXML)));
			Element root = doc.getDocumentElement();
			NodeList nodes = root.getChildNodes();
			if (nodes != null) {
				for (int i = 0; i < nodes.getLength(); i++) {
					Node node = nodes.item(i);
					if(node.getNodeName().equals("returnstatus")){
						if(node.getTextContent().equals("Success")){
							j.setSuccess(true);
						}
					}
					if(node.getNodeName().equals("message")){
						j.setMsg(node.getTextContent());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}
}
